import {RouteLocationNormalized, RouteRecordRaw} from 'vue-router';
import {useUserStore} from '@/store';
import {SUPER_ADMIN_KEY} from '@/router/constants';

export default function usePermission() {
    const userStore = useUserStore();
    return {
        accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
            if (!route.meta?.requiresAuth || !route.meta?.roles) {
                return true;
            }
            // 是否是超级管理员
            if (userStore.roles.includes(SUPER_ADMIN_KEY)) {
                return true;
            }
            // 登陆用户是否包含某个角色
            for (let i = 0; i < userStore.roles.length; i++) {
                if (route.meta?.roles?.includes(userStore.roles[i])) {
                    return true;
                }
            }
            return (
                route.meta?.roles?.includes(SUPER_ADMIN_KEY)
            );
        },
        findFirstPermissionRoute(_routers: any, role = 'admin') {
            const cloneRouters = [..._routers];
            while (cloneRouters.length) {
                const firstElement = cloneRouters.shift();
                if (
                    firstElement?.meta?.roles?.find((el: string[]) => {
                        return el.includes(SUPER_ADMIN_KEY) || el.includes(role);
                    })
                )
                    return {name: firstElement.name};
                if (firstElement?.children) {
                    cloneRouters.push(...firstElement.children);
                }
            }
            return null;
        },
        // You can add any rules you want
    };
}
